package com.neoCalf.neoUser.webSocket.tool;


import com.neoCalf.neoCommon.redis.RedisComponent;
import com.neoCalf.neoCommon.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class WsDataTool {
    @Resource
    private RedisComponent<String> redisComponent;
    @Resource
    private JwtUtil<Long> jwtUtil;

    public String decodeParamToString(WebSocketServerProtocolHandler.HandshakeComplete complete, String name) {
        return (String) decodeParamToObject(complete, name);
    }

    public Integer decodeParamToInteger(WebSocketServerProtocolHandler.HandshakeComplete complete, String name) {
        return (Integer) decodeParamToObject(complete, name);
    }

    public Object decodeParamToObject(WebSocketServerProtocolHandler.HandshakeComplete complete, String name) {
        String uri = complete.requestUri();
        if (!uri.contains("?")) {
            return null;
        }
        if (!uri.contains(name + "=")) {
            return null;
        }
        return uri.split(name + "=", 2)[1].split("&", 2)[0];
    }

    public Object getValueByToken(String token, String key) {
        Claims claims = jwtUtil.parseJwtToken(token);
        return claims.get(key);
    }

    public String getUserIdByChannel(Channel channel) {
        String valueByChannel = getValueByChannel(channel);
        if (valueByChannel == null) {
            return null;
        }
        String[] split = valueByChannel.split("\n");
        return split[0];
    }

    public String getTokenByChannel(Channel channel) {
        String valueByChannel = getValueByChannel(channel);
        if (valueByChannel == null) {
            return null;
        }
        String[] split = valueByChannel.split("\n");
        return split[1];
    }

    public String getValueByChannel(Channel channel) {
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        return attribute.get();
    }

    public void saveUserHeartBeat(String userId) {
        redisComponent.addUserHeartBeat(userId);
    }

    public void delUserHeartBeat(String userId) {
        redisComponent.delUserHeartBeat(userId);
    }
}
